package com.magnusart.scrumppm.presenters;

import java.util.Observable;
import java.util.Observer;

import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

import com.magnusart.scrumppm.gui.MenuBar;
import com.magnusart.scrumppm.gui.MenuBar.MenuItems;
import com.magnusart.scrumppm.model.States;
import com.magnusart.scrumppm.model.States.Transition;

public final class MenuPresenter implements Observer, Listener
{

	private final MenuBar menuBar;
	
	public MenuPresenter( MenuBar menuBar) {
		
		this.menuBar = menuBar;
		initMenu();
		addListeners();
	}

	private void initMenu() {
		// Is enabled when program starts.
		menuBar.getOpenProjectItem().setEnabled( false );
	}
	
	private void addListeners() {
		menuBar.getNewProjectItem().addListener( SWT.Selection, this );
		menuBar.getOpenProjectItem().addListener( SWT.Selection, this );
	}

	@Override
	public void handleEvent( Event e ) {
		if( e.widget.getData() instanceof MenuItems ) {
			MenuItems s = (MenuItems)( e.widget.getData() );
			switch( s ) {
			case NewProject:
				Transition.to( Transition.MENU_TO_NEW );
				break;
			case OpenProject:
				Transition.to( Transition.MENU_TO_CHOOSER );
				break;
			case AboutProgram:
				break;
			}
		}
	}
	
	@Override
	public void update( Observable obs, Object obj ) {
		if( obs.equals( States.observe() ) && obj instanceof Transition ) {
			// This is an transition
			Transition trans = (Transition) obj;
			
			switch( trans.dst ) {
				case PROJECT_CREATE_NEW:
					menuBar.getOpenProjectItem().setEnabled( true );
					menuBar.getNewProjectItem().setEnabled( false );
					break;
				case PROJECT_CHOOSER:
					menuBar.getOpenProjectItem().setEnabled( false );
					menuBar.getNewProjectItem().setEnabled( true );
					break;
				case PROJECT_DETAILS:
					menuBar.getOpenProjectItem().setEnabled( true );
					menuBar.getNewProjectItem().setEnabled( true );
					break;
			}
		}
	}
}
